package xyz.syyrjx.blog.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.dao.ai.AiIdentityDao;
import xyz.syyrjx.blog.dao.ai.AiIdentityGradeDao;
import xyz.syyrjx.blog.dao.ai.AiModelDao;
import xyz.syyrjx.blog.entity.ai.AiIdentity;
import xyz.syyrjx.blog.entity.ai.AiIdentityGrade;
import xyz.syyrjx.blog.entity.ai.AiModel;
import xyz.syyrjx.blog.exception.AiException;
import xyz.syyrjx.blog.service.AiService;
import xyz.syyrjx.blog.util.CachePool;
import xyz.syyrjx.blog.util.ConstValuePool;
import xyz.syyrjx.blog.util.ai.*;
import xyz.syyrjx.blog.util.identity.IdentityCheckUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/2/4 12:44
 * @description ...
 * @since v0.0.1
 */
@Service
public class AiServiceImpl implements AiService {

    private static final Logger logger = LoggerFactory.getLogger(AiServiceImpl.class);

    @Resource
    private AiIdentityDao aiIdentityDao;
    @Resource
    private AiIdentityGradeDao aiIdentityGradeDao;
    @Resource
    private AiModelDao aiModelDao;

    @Resource
    private QwenModelService qwenModelService;
    @Resource
    private ChatGptModelService chatGptModelService;
    @Resource
    private Gpt4ModelService gpt4ModelService;

    @Resource
    private WanxModelService wanxModelService;

    @Override
    public String getAnswer(String model, String prompt, HttpServletRequest request, HttpServletResponse response) {
//        logger.info("执行到service");
        AiModelService aiModelService = null;
        String usageCountFlag = null;
        int maxUsageCount = 0;
//        logger.info("执行到判断模型");
        switch (model) {
            case ConstValuePool.QWEN_MODEL:
                aiModelService = this.qwenModelService;
                usageCountFlag = ConstValuePool.QWEN_USAGE_COUNT;
                maxUsageCount = CachePool.aiIdGradeCountMap
                        .get(ConstValuePool.QWEN_USAGE_COUNT)
                        .get(0);
                break;
            case ConstValuePool.CHATGPT_MODEL:
                aiModelService = this.chatGptModelService;
                usageCountFlag = ConstValuePool.CHAT_USAGE_COUNT;
                maxUsageCount = CachePool.aiIdGradeCountMap
                        .get(ConstValuePool.CHAT_USAGE_COUNT)
                        .get(0);
                break;
            case ConstValuePool.GPT4_MODEL:
                aiModelService = gpt4ModelService;
                usageCountFlag = ConstValuePool.GPT4_USAGE_COUNT;
                maxUsageCount = CachePool.aiIdGradeCountMap
                        .get(ConstValuePool.GPT4_USAGE_COUNT)
                        .get(0);
                break;
            case ConstValuePool.WANX_MODEL:
                aiModelService = this.wanxModelService;
                usageCountFlag = ConstValuePool.WANX_USAGE_COUNT;
                maxUsageCount = CachePool.aiIdGradeCountMap
                        .get(ConstValuePool.WANX_USAGE_COUNT)
                        .get(0);
                break;
            default:
                throw  new AiException("未选择模型");
        }
        // 非管理员需要进行次数检查
//        logger.info("执行到身份检查");
        HttpSession session = request.getSession();
        String id = AiIdentityFlagUtil.checkAiIdentity(request,response);;
        if (!IdentityCheckUtil.isAdmin(session)) {
            // 检查对话次数
            AiUseCheckUtil.usageCheck( id, usageCountFlag
                    , usageCountFlag, maxUsageCount);
        }
        // 简易锁
        if (CachePool.SIMPLE_AI_DIALOG_LOCK_MAP.containsKey(id)) {
            throw new AiException("您的上一次对话未结束，无法发起新一轮对话");
        }

//        logger.info("执行到ai调用");
        try {
            CachePool.SIMPLE_AI_DIALOG_LOCK_MAP.put(id,Boolean.TRUE);
            return aiModelService.answer(prompt,request , id);
        }catch (InterruptedException e) {
            throw new AiException("", e);
        }finally {
            CachePool.SIMPLE_AI_DIALOG_LOCK_MAP.remove(id);
        }
    }


    @Override
    public void setAiIdentityGrade(String id, int grade) {
        AiIdentity aiIdentity
                = aiIdentityDao.selectAiIdentity(new AiIdentity(null, id, null, State.NORMAL_STATE.getCode()));
        aiIdentityGradeDao.deleteIdentityByIdentityId(aiIdentity.getId());
        AiIdentityGrade aiIdentityGrade = new AiIdentityGrade(null, aiIdentity.getId() , grade, State.NORMAL_STATE.getCode());
        aiIdentityGradeDao.insertIdentityGrade(aiIdentityGrade);
    }

    @Override
    public List<AiModel> getAllAiModels() {
        return aiModelDao.selectAllAiModels();
    }
}
